package mylog

import (
	"log"
	"os"
	"path"
	"time"

	"gitee.com/githubdog/goci/tools/helper"
)

var (
	DefaultDirPerm  os.FileMode = 0755
	DefaultFilePerm os.FileMode = 0644
	logRootPath     string
)

// InitLog 初始化日志
func InitLog(_logRootPath string) (err error) {
	if err = helper.CheckAndMkDir(_logRootPath, DefaultDirPerm); err == nil {
		logRootPath = helper.CheckEndString(_logRootPath, true)
	}
	return
}

func getTodayLogFileName() string {
	return time.Now().Format(helper.GetDateFormat("Y-m-d")) + ".log"
}

func getDefaultFileName(fname string) string {
	if fname == "" {
		fname = getTodayLogFileName()
	} else if fname != "/" && path.Ext(fname) == "" {
		fname += ".log"
	}
	return fname
}

// WriteLog 写日志
func WriteLog(channel, fname string, vals ...interface{}) {
	if err := helper.CheckAndMkDir(logRootPath+channel, DefaultDirPerm); err == nil {
		writeContent(logRootPath+channel+"/"+getDefaultFileName(fname), vals...)
	}
}

func writeContent(filename string, vals ...interface{}) {
	if f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, DefaultFilePerm); err == nil {
		defer f.Close()
		log.SetOutput(f)
		log.Println(vals...)
		log.SetOutput(os.Stdout)
	}
}
